package com.tangkun.environment.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;

import com.tangkun.environment.R;
import com.tangkun.environment.activity.SplashActivity;
import com.tangkun.environment.network.GlobalUrl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author xiongfeng.li
 * @Description 版本升级后台类
 */
public class SoftwareService extends Service {
    private String ApkUrl = "";// 下载路径
    private File updateDir = null;// apk文件保存路径
    private String versonName = "environment.apk";// 临时存放的文件名
    private File updateFile = null;
    private NotificationManager updateNotificationManager = null;// 通知栏管理类
    private Notification updateNotification = null;
    private Intent updateIntent = null;
    private PendingIntent updatePendingIntent = null;
    private final static int DOWNLOAD_COMPLETE = 0;// 下载成功
    private final static int DOWNLOAD_FAIL = 1;// 下载失败

    private Handler handler = new Handler() {
        @SuppressWarnings("deprecation")
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_COMPLETE:
                    installApk();
                    updateNotificationManager.cancel(0);
                    break;
                case DOWNLOAD_FAIL:
                    // 下载失败
                    //用这段代码替代下面注释代码
                    contentView.setTextViewText(R.id.notificationTitle,
                            getString(R.string.app_name));
                    updateNotification.tickerText = "下载失败";
                    updatePendingIntent = PendingIntent.getActivity(SoftwareService.this, 0, updateIntent,
                            0);
                    updateNotification.contentIntent = updatePendingIntent;
//                    updateNotification.setLatestEventInfo(SoftwareService.this,
//                            getString(R.string.app_name), "下载失败",
//                            updatePendingIntent);
                    updateNotificationManager.notify(0, updateNotification);
                    updateNotificationManager.cancel(0);
                    break;
                default:
                    updateNotificationManager.cancel(0);
                    break;
            }
        }
    };

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    RemoteViews contentView;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent == null) {
            return Service.START_STICKY_COMPATIBILITY;
        }
        ApkUrl = intent.getStringExtra("url");
        // 创建文件
        if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment
                .getExternalStorageState())) {
            updateDir = new File(GlobalUrl.CACHE_PATH);
            updateFile = new File(updateDir.getPath(), versonName);
            try {
                if (!updateDir.exists()) {
                    updateDir.mkdirs();
                }
                if (!updateFile.exists()) {
                    updateFile.createNewFile();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        this.updateNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        this.updateNotification = new Notification();
        // 设置通知栏显示内容
        updateNotification.icon = R.mipmap.ic_launcher;
        updateNotification.tickerText = "开始下载";
        updateNotification.when = System.currentTimeMillis();
        updateNotification.flags = Notification.FLAG_NO_CLEAR;
        // 显示进度条部分
        contentView = new RemoteViews(getPackageName(), R.layout.versionup);
        contentView.setTextViewText(R.id.notificationTitle,
                getString(R.string.app_name));
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        updateNotification.contentView = contentView;
        // 设置下载过程中，点击通知栏，回到主界面
        updateIntent = new Intent(this, SplashActivity.class);
        updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        updatePendingIntent = PendingIntent.getActivity(this, 0, updateIntent,
                0);
        updateNotification.contentIntent = updatePendingIntent;

        // 发出通知
        updateNotificationManager.notify(0, updateNotification);
        // 开启一个新的线程下载，如果使用Service同步下载，会导致ANR问题，Service本身也会阻塞
        new Thread(new updateRunnable()).start();// 这个是下载的重点，是下载的过程

        return super.onStartCommand(intent, flags, startId);

    }

    class updateRunnable implements Runnable {
        Message message = handler.obtainMessage();

        public void run() {
            try {// 下载成功
                long downloadSize = downloadUpdateFile(ApkUrl, updateFile);
                if (downloadSize > 0) {
                    message.what = DOWNLOAD_COMPLETE;
                    handler.sendMessage(message);
                }
            } catch (Exception ex) {// 下载失败
                ex.printStackTrace();
                message.what = DOWNLOAD_FAIL;
                handler.sendMessage(message);
            }
        }
    }

    public long downloadUpdateFile(String downloadUrl, File saveFile)
            throws Exception {
        int downloadCount = 0;
        int currentSize = 0;
        long totalSize = 0;
        int updateTotalSize = 0;
        HttpURLConnection httpConnection = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL(downloadUrl);
            httpConnection = (HttpURLConnection) url.openConnection();
            httpConnection
                    .setRequestProperty("User-Agent", "PacificHttpClient");
            if (currentSize > 0) {
                httpConnection.setRequestProperty("RANGE", "bytes="
                        + currentSize + "-");
            }
            httpConnection.setConnectTimeout(10000);
            httpConnection.setReadTimeout(20000);
            updateTotalSize = httpConnection.getContentLength();
            if (httpConnection.getResponseCode() == 404) {
                throw new Exception("fail!");
            }
            is = httpConnection.getInputStream();
            fos = new FileOutputStream(saveFile, false);
            byte buffer[] = new byte[4096];
            int readsize = 0;
            while ((readsize = is.read(buffer)) > 0) {
                fos.write(buffer, 0, readsize);
                totalSize += readsize;
                // 为了防止频繁的通知导致应用吃紧，百分比增加5才通知一次
                if ((downloadCount == 0)
                        || (int) (totalSize * 100 / updateTotalSize) - 5 >= downloadCount) {
                    downloadCount += 5;
                    contentView.setTextViewText(R.id.notificationTitle,
                            getString(R.string.app_name));
                    contentView.setTextViewText(R.id.notificationPercent,
                            (int) totalSize * 100 / updateTotalSize + "%");
                    contentView.setProgressBar(R.id.notificationProgress, 100,
                            (int) totalSize * 100 / updateTotalSize, false);
                    updateNotificationManager.notify(0, updateNotification);
                }
            }
        } finally {
            if (httpConnection != null) {
                httpConnection.disconnect();
            }
            if (is != null) {
                is.close();
            }
            if (fos != null) {
                fos.close();
            }
        }
        return totalSize;
    }

    /**
     * 安装文件的方法
     */
    public void installApk() {
        Uri uri = Uri.fromFile(updateFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        stopSelf();
    }
}


